package com.qydp.rpc.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.qydp.rpc.model.RequestModel;
import com.qydp.rpc.model.ResponseModel;
import com.qydp.rpc.serializer.JdkSerializer;
import com.qydp.rpc.serializer.Serializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author shuSheng
 * @description
 * @since 2024-07-23 16:59
 */
public class ProxyUtils implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("ProxyUtils proxy:" + method);
        RequestModel requestModel = new RequestModel();
        requestModel.setServiceName(method.getDeclaringClass().getName());
        requestModel.setMethodName(method.getName());
        requestModel.setParameterTypes(method.getParameterTypes());
        requestModel.setArgs(args);

        Serializer jdkSerializer = new JdkSerializer();
        System.out.println("入参数: " + JSONUtil.toJsonStr(requestModel));
        byte[] serialize = jdkSerializer.serialize(requestModel);

        HttpResponse response = HttpRequest.post("http://127.0.0.1:8081").body(serialize).execute();
        System.out.println("出参数: " + response.body());
        byte[] bytes = response.bodyBytes();
        ResponseModel responseModel = jdkSerializer.deserialize(bytes, ResponseModel.class);
        System.out.println("出参数: " + JSONUtil.toJsonStr(responseModel));
        return responseModel.getResult();

    }

    public static <T> T getProxy(Class<T> serverClass) {
        return (T) Proxy.newProxyInstance(serverClass.getClassLoader(), new Class[]{serverClass}, new ProxyUtils());
    }
}
